// pages/service/bind-doctor/index.ts
import { getDoctorBaseInfoByIdBind, bindDoctorApi } from '../../../utils/api/bindDoctor'
import userBaseInfoState from '../../../stores/userBaseInfo'
import Notify from '@vant/weapp/notify/notify';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scanCode: <any>null,
    showInputDialog: false,
    doctorUid: <string | number | null>'',
    showDoctorInfo: false,
    doctorInfo: <PatientBaseEntity | null>null,
  },
  getDoctorInfo(doctorUid: string | number) {
    // 根据传入的doctorUid获取doctorInfo
    console.log('获取得到的ID', doctorUid);
    getDoctorBaseInfoByIdBind(doctorUid).then((res: any) => {
      // 如果为空，那么不显示，提示医生信息为空
      if (res.data == null) {
        Notify({ type: 'danger', message: '不存在该医生' });
        return;
      }
      // 获取医生信息
      this.setData({
        doctorInfo: res.data,
      })

      // 展示医生信息
      this.setData({
        showDoctorInfo: true,
      })
      // 触发更新函数
      let doctorInfoComponent = this.selectComponent('#doctor-info');
      doctorInfoComponent.updateDoctorInfo();

    }).catch((err: any) => {
      console.log("获取医生信息出现异常信息", err);
    })

  },

  scanCodeEvent() {
    var that = this;
    wx.scanCode({
      success(res) {
        that.setData({
          doctorUid: res.result
        })
        // 扫码成功后  在此处理接下来的逻辑
        that.getDoctorInfo(res.result)
      }
    })
  },
  inputCodeEvent() {
    this.setData({
      showInputDialog: true,
    })
  },
  getUserInfo(event: any) {
    console.log(event.detail);
  },
  confirmInput() {
    if (this.data.doctorUid && this.data.doctorUid != '') {
      this.getDoctorInfo(this.data.doctorUid)
    }
  },
  changDoctorUid(event: any) {
    this.setData({
      doctorUid: event.detail,
    })
  },

  confirmBind() {
    console.log('获取的doctorUid是', this.data.doctorUid);
    // 确认绑定医生信息
    const data = {
      doctorUid: this.data.doctorUid,
      patientUid: userBaseInfoState.data.patientUid,
    }
    bindDoctorApi(data).then((res: any) => {
      wx.showToast({
        title: '绑定医生成功',
        icon: 'success',
      })
    }).catch((res: any) => {
      wx.showModal({
        title:'绑定医生失败',
        content: res.msg,
      })
      console.log('绑定医生失败',res);
    }).finally(() => {
      this.setData({
        showDoctorInfo: false,
      })
    })
  },
  cancelBind() {
    this.setData({
      showDoctorInfo: false,
      doctorUid: ''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})